package com.link.linkupjavaweb.controller.user;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.dto.UserLoginDTO;
import com.link.linkupjavaweb.dto.UserRegisterDTO;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

/**
 * 用户认证Controller
 */
@Controller
@RequestMapping("/user")
public class UserAuthController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 跳转到登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "user/login";
    }
    
    /**
     * 跳转到注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "user/register";
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ResponseBody
    public Result<User> login(@RequestBody UserLoginDTO loginDTO, HttpSession session) {
        try {
            User user = userService.login(loginDTO);
            // 将用户信息存入Session
            session.setAttribute(Constants.SESSION_USER, user);
            return Result.success("登录成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ResponseBody
    public Result<String> register(UserRegisterDTO registerDTO, 
                                   @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile) {
        try {
            String account = userService.register(registerDTO, avatarFile);
            return Result.success("注册成功！您的账号是：" + account, account);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 获取用户信息
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user != null) {
            // 更新在线状态为离线
            userService.updateOnlineStatus(user.getId(), Constants.ONLINE_STATUS_OFFLINE);
        }
        // 清除Session
        session.removeAttribute(Constants.SESSION_USER);
        session.invalidate();
        return "redirect:/user/login";
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/current")
    @ResponseBody
    public Result<User> getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user == null) {
            return Result.error("未登录");
        }
        return Result.success(user);
    }
}

